/**
 * @author Mak
 * @name kh_utils 插件
 * @Date 2017-03-15 16:17:08
 * @type {{isNull: ((T?)), isNullStrict: ((T?))}}
 * 自定义工具插件
 */
"use strict";
import Vue from 'vue'
var utils = {
  /**判断是否未定义**/
  isUndefined(T) {
    var res = false;
    if (T == null || T == undefined) {
      res = true;
    }
    return res;
  },
  /**判断是否为空**/
  isNull(T) {
    var res = false;
    if (this.isUndefined(T) || T === '') {
      res = true;
    }
    return res;
  },
  /**严格判断是否为空**/
  isNullStrict(T) {
    var res = false;
    if (this.isUndefined(T) || T === 'null' || T === '' || T === 'NULL' || T === 'Null') {
      res = true;
    }
    return res;
  },
  /**日期格式化**/
  formatDate(date, fmt) {
    if (date == undefined) {
      return date;
    }
    if (!(date instanceof Date)) {
      date = new Date(date);
    }
    var o = {
      "M+": date.getMonth() + 1, //月份
      "d+": date.getDate(), //日
      "h+": date.getHours(), //小时
      "m+": date.getMinutes(), //分
      "s+": date.getSeconds(), //秒
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度
      "S": date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));

    return fmt;
  },

  /**日期格式化**/
  formatDateDifBrowser(date, fmt) {
    if (date == undefined) {
      return date;
    }
    if (!(date instanceof Date)) {
      // 解决火狐显示日期显示 NaN 的问题
      date = "2001-" + date + ":00"
      date = date.replace(/-/g, ':').replace(' ', ':');
      date = date.split(':');
      date = new Date(date[0], (date[1] - 1), date[2], date[3], date[4], date[5]);
    }
    var o = {
      "M+": date.getMonth() + 1, //月份
      "d+": date.getDate(), //日
      "h+": date.getHours(), //小时
      "m+": date.getMinutes(), //分
      "s+": date.getSeconds(), //秒
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度
      "S": date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));

    return fmt;
  },
  /**
   * 对比时间
   * @param date1
   * @param date2
   * @param fmt
   * @returns {*}
   */
  isSameDate(date1, date2, fmt) {
    let d1 = this.formatDate(date1, fmt);
    let d2 = this.formatDate(date2, fmt);
    if (d1 == d2) {
      return true;
    }
    return false;
  },
  /**判断是否为电话号码**/
  isTel(T) {
    let reg = /^0\d{2,3}-?\d{7,8}$/;
    return reg.test(T);
  },
  /**判断是否为手机号码**/
  isMobile(T) {
    // let reg = /^1[3|5|8][0-9]\d{4,8}$/;
    let reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
    return reg.test(T);
  },
  /**判断是否为邮箱**/
  isEmail(T) {
    let reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return reg.test(T);
  },
  /**判断是否为中文名**/
  isChineseName(T) {
    let reg = /^[\u4E00-\u9FA5]{2,4}$/
    return reg.test(T);
  },
  /**如果为空即转换为 str**/
  nullToStr(T, Str) {
    return T = this.isNull(T) ? Str : T;
  },
  /**判断是否身份证正确**/
  isCardNo(T){
    let reg =  /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    return reg.test(T);
  },
  /**拷贝对象**/
  clone(T) {
    var newObj = {};
    if (val instanceof Date) { //拷贝Date对象会造成栈溢出
      newObj = val;
    } else {
      if (T instanceof Array) {
        newObj = [];
      }
      for (var key in T) {
        var val = T[key];
        newObj[key] = typeof val === 'object' ? this.clone(val) : val;
      }
      if(T===null)newObj = null
    }
    return newObj;
  },
  /**数组去重**/
  unique(arr) {
    return Array.from(new Set(arr));
  },
  /**绑定数据**/
  bindingBean(T, Y) {
    var _this = this;
    if (!_this.isUndefined(T) && !_this.isUndefined(Y)) {
      for (var key in T) {
        var val = Y[key];
        if (!_this.isUndefined(val)) {
          //T[key] = typeof val === 'object' ? this.clone(val) : String(val);
          if (typeof val === 'object'){
            T[key] = this.clone(val);
          }else if(typeof val === 'number'){
            T[key] = Number(val);
          }else{
            T[key] = String(val);
          }
        }
      }
    }
    return T;
  },
  /**绑定属性**/
  bindProps(T, Y) {
    for (let key in T) {
      for (let p of Y) {
        if (p.cd == key) {
          T[key] = p.para_value;
          if (T[key] == undefined) {
            T[key] = '';
          }
          break;
        }
      }
    }
  },
  //清空数据
  clearData(T, boolean) {
    for (let key in T) {
      if (key == "id") {
        delete T[key];
      } else if (T[key] instanceof Array) {
        T[key] = [];
      } else if (T[key] instanceof Boolean) {
        T[key] = boolean;
      } else if (T[key] instanceof Object) {
        T[key] = {};
      } else if (T[key] instanceof Number) {
        T[key] = null;
      } else {
        T[key] = '';
      }
    }
  },
  //检查对象是否为空
  isEmptyObject(e) {
    var t;
    for (t in e)
      return !1;
    return !0
  },
  /**
   * 标准数字格式化
   * @param value
   * @param fix 保留小数
   * @param pre 保留位数
   * @param flag 是否启用科学计数法
   * @returns {string|*}
   */
  formatterNum(value, fix, pre, flag) {
    if (value != undefined && String.trim(value) != "") {
      value = new Number(value);
      value = value.toFixed(fix);
      if (pre) {
        if (!flag) {
          if (value > 1 && value < 1000) {
            value = new Number(value).toPrecision(3);
          } else if (value >= 1000) {
            value = String(value);
            value = value.split(".")[0];
          }
        } else {
          value = new Number(value).toPrecision(pre);
        }
      }
      return value;
    }
  },
  mathRand() {
    var Num = "";
    for (var i = 0; i < 6; i++) {
      Num += Math.floor(Math.random() * 10);
    }
    return Num;
  },
  mathRand19() {
    var Num = "";
    for (var i = 0; i < 6; i++) {
      Num += Math.floor(Math.random() * 10);
    }
    //return new Date().getTime() + Num;
    return this.formatDateString(new Date(),"yyyyMMddHHmmss") + Num;
  },
  elIsPhone(rule, value, callback){
    if (!value){
      return callback(new Error('手机号不能为空'));
    } else{
      let reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
      if (reg.test(value)){
        callback();
      } else{
        return callback(new Error('请输入正确的手机号'));
      }
    }
  },
  elIsCardNo(rule, value ,callback){
    if (!value){
      return callback(new Error('身份证号码不能为空'));
    } else{
      let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (reg.test(value)){
        callback();
      } else{
        return callback(new Error('请输入正确的身份证号码'));
      }
    }
  },
  elIsMali(rule, value, callback){
    if (!value){
      return callback(new Error('邮箱不能为空'));
    } else{
      let reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
      if (reg.test(value)){
        callback();
      } else{
        return callback(new Error('请输入正确的邮箱'));
      }
    }
  },
  // 根据文件名后缀区分 文件类型
  /*
   * @param: fileName - 文件名称
   * @param: 数据返回 1) 无后缀匹配 - false
   * @param: 数据返回 2) 匹配图片 - image
   * @param: 数据返回 3) 匹配 txt - txt
   * @param: 数据返回 4) 匹配 excel - excel
   * @param: 数据返回 5) 匹配 word - word
   * @param: 数据返回 6) 匹配 pdf - pdf
   * @param: 数据返回 7) 匹配 ppt - ppt
   * @param: 数据返回 8) 匹配 视频 - video
   * @param: 数据返回 9) 匹配 音频 - radio
   * @param: 数据返回 10) 其他匹配项 - other
   */
  matchType(fileName) {
    // 后缀获取
    var suffix = '';
    // 获取类型结果
    var result = '';
    try {
      var flieArr = fileName.split('.');
      suffix = flieArr[flieArr.length - 1].toLowerCase();
    } catch (err) {
      suffix = '';
    }
    // fileName无后缀返回 false
    if (!suffix) {
      result = false;
      return result;
    }
    // 匹配 pdf
    var pdflist = ['pdf'];
    result = pdflist.some(function (item) {
      return item == suffix;
    });
    if (result) {
      result = 'pdf';
      return result;
    };
    // 图片格式
    var imglist = ['png', 'jpg', 'jpeg', 'bmp'];
    // 进行图片匹配
    result = imglist.some(function (item) {
      return item == suffix;
    });
    if (result) {
      result = 'image';
      return result;
    };
    // 匹配txt
    var txtlist = ['txt'];
    result = txtlist.some(function (item) {
      return item == suffix;
    });
    if (result) {
      result = 'txt';
      return result;
    };
    // 匹配 excel
    var excelist = ['xls', 'xlsx'];
    result = excelist.some(function (item) {
      return item == suffix;
    });
    if (result) {
      result = 'excel';
      return result;
    };
    // 匹配 word
    var wordlist = ['doc', 'docx'];
    result = wordlist.some(function (item) {
      return item == suffix;
    });
    if (result) {
      result = 'word';
      return result;
    };
    // 匹配 ppt
    var pptlist = ['ppt'];
    result = pptlist.some(function (item) {
      return item == suffix;
    });
    if (result) {
      result = 'ppt';
      return result;
    };
    // 匹配 视频
    var videolist = ['mp4', 'm2v', 'mkv'];
    result = videolist.some(function (item) {
      return item == suffix;
    });
    if (result) {
      result = 'video';
      return result;
    };
    // 匹配 音频
    var radiolist = ['mp3', 'wav', 'wmv'];
    result = radiolist.some(function (item) {
      return item == suffix;
    });
    if (result) {
      result = 'radio';
      return result;
    }
    // 其他 文件类型
    result = 'other';
    return result;
  },
  numberToChinese(num){
    var AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十");
    var BB = new Array("", "十", "百", "仟", "萬", "億", "点", "");
    var a = ("" + num).replace(/(^0*)/g, "").split("."),
      k = 0,
      re = "";
    for (var i = a[0].length - 1; i >= 0; i--) {
      switch (k) {
        case 0:
          re = BB[7] + re;
          break;
        case 4:
          if (!new RegExp("0{4}//d{" + (a[0].length - i - 1) + "}$")
            .test(a[0]))
            re = BB[4] + re;
          break;
        case 8:
          re = BB[5] + re;
          BB[7] = BB[5];
          k = 0;
          break;
      }
      if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0)
        re = AA[0] + re;
      if (a[0].charAt(i) != 0)
        re = AA[a[0].charAt(i)] + BB[k % 4] + re;
      k++;
    }

    if (a.length > 1) // 加上小数部分(如果有小数部分)
    {
      re += BB[6];
      for (var i = 0; i < a[1].length; i++)
        re += AA[a[1].charAt(i)];
    }
    if (re == '一十')
      re = "十";
    if (re.match(/^一/) && re.length == 3)
      re = re.replace("一", "");
    return re;
  },

  notifySuccess(message) { // 接口成功調取時成功信息提示
    if (!message){
      message = '操作成功'
    }
    //Vue.prototype.$notify({
    Vue.prototype.$notify({
      type: 'success',
      title: '成功',
      message: message,
      duration: 3000
    })
  },
  notifyError(message) { // 接口成功調取時失败信息提示
    if (!message){
      message = '操作失败'
    }
    Vue.prototype.$notify({
      type: 'error',
      title: '失败',
      message: message,
      duration: 5000
    })
  },
  notifyWarn(message) { // 接口成功調取時成功信息提示
    if (!message){
      message = '操作错误'
    }
    Vue.prototype.$notify({
      type: 'warning',
      title: '提示',
      message: message,
      duration: 5000
    })
  },
  /**
   * 请求内容需要提示时 使用该提示
   * @param {*} type 提示类型
   * @param {*} message 提示信息
   * @param {*} duration 持续时间
   */
  notify(type, message, duration) {
    Vue.prototype.$notify({
      type: type,
      title: type === 'success' ? '成功' : (type === 'error' ? '失败' : '提示'),
      message: message || '',
      duration: duration || 0
    })
  },

  messageSuccess(message) {
    if (!message){
      message = '操作成功'
    }
    //Vue.prototype.$notify({
    Vue.prototype.$message({
      type: 'success',
      title: '成功',
      message: message,
      duration: 3000
    })
  },
  messageError(message) {
    if (!message){
      message = '操作失败'
    }
    //Vue.prototype.$notify({
    Vue.prototype.$message({
      type: 'error',
      title: '失败',
      message: message,
      duration: 3000
    })
  },
  messageWarn(message) { // 接口成功調取時成功信息提示
    if (!message){
      message = '操作错误'
    }
    Vue.prototype.$message({
      type: 'warning',
      title: '提示',
      message: message,
      duration: 5000
    })
  },
  /**
   * 校验时 使用该提示类型
   * @param {*} type 提示类型
   * @param {*} message 提示内容
   * @param {*} showClose 是否可关闭
   * @param {*} center 是否剧中
   * @param {*} duration 持续时间
   */
  message(type,message,showClose,center,duration){
    Vue.prototype.$message({
      title: message,
      type: type || '',
      showClose: showClose, // true/false
      center: center,
      duration: duration
    })
  },

  // 获取文件名
  getFileNameByUrl(url) {
    let http = url.split('?')[0];
    let file = http.split('/');
    let lastFile = file[file.length - 1];
    let name = lastFile.split('.')[0];
    return name;
  },

  // 本地文件下载
  downloadFile(url, fileName) {
    var a = document.createElement('a')
    a.download = fileName
    a.target = '_blank'
    a.href = '//' + document.domain + '/' + url
    a.click()
  },

  // 网络图片单个文件下载
  downloadByBlob(url,name) {
    let image = new Image()
    image.setAttribute('crossOrigin', 'anonymous')
    image.src = url
    image.onload = () => {
      let canvas = document.createElement('canvas')
      canvas.width = image.width
      canvas.height = image.height
      let ctx = canvas.getContext('2d')
      ctx.drawImage(image, 0, 0, image.width, image.height)
      canvas.toBlob((blob) => {
        let url = URL.createObjectURL(blob)
        let eleLink = document.createElement('a')
        eleLink.download = name
        eleLink.href = url
        eleLink.click()
        eleLink.remove()
        // 用完释放URL对象
        URL.revokeObjectURL(url)
      })
    }
  },

  // 批量下载文件
  downloadFiles(ids,url) {
    url = process.env.BASE_API+url
    var dlform = document.createElement('form');
    dlform.style = "display:none;";
    dlform.method = 'post';
    dlform.action = url;
    dlform.target = 'callBackTarget';
    var hdnFilePath = document.createElement('input');
    hdnFilePath.type = 'hidden';
    hdnFilePath.name = 'ids';
    hdnFilePath.value = ids;
    dlform.appendChild(hdnFilePath);
    document.body.appendChild(dlform);
    dlform.submit();
    document.body.removeChild(dlform);
  },


  // 判断两个数组是否相差正负1
  arrayContrast(a,b) {
    if (a.length != b.length){
      return false;
    }
    let as = a.match(/./g);
    let bs = b.match(/./g);
    let lgt = a.length;
    a="";
    b="";
    const set = new Set();
    for (let i = 0;i<lgt;i++){
      set.add(as[i]);
      if (!set.has(bs[i])){
        a+=as[i];
        b+=bs[i];
      }
      set.clear();
    }
    let an = Number(a);
    let bn = Number(b);
    if(bn-an>1 || bn-an<-1){
      return false;
    }
    return true;
  },

  formatDateString(date, format = "yyyy-MM-dd HH:mm:ss") {
    if(typeof date === 'number') date = new Date(date)
    if (date instanceof Date) {
      const year = date.getFullYear().toString();
      const month = (date.getMonth() + 1).toString();
      const month2 = month.length > 1 ? month : "0" + month;
      const day = date.getDate().toString();
      const day2 = day.length > 1 ? day : "0" + day;
      const hours = date.getHours().toString();
      const hours2 = hours.length > 1 ? hours : "0" + hours;
      const minutes = date.getMinutes().toString();
      const minutes2 = minutes.length > 1 ? minutes : "0" + minutes;
      const seconds = date.getSeconds().toString();
      const seconds2 = seconds.length > 1 ? seconds : "0" + seconds;

      return format
        .replace("yyyy", year)
        .replace("MM", month2)
        .replace("M", month)
        .replace("dd", day2)
        .replace("d", day)
        .replace("HH", hours2)
        .replace("H", hours)
        .replace("mm", minutes2)
        .replace("m", minutes)
        .replace("ss", seconds2)
        .replace("s", seconds);
    }
  },

  removeSelectReadOnly(){
    Array.from(document.getElementsByClassName('el-select')).forEach((item) => {
      item.children[0].children[0].removeAttribute('readonly')
      item.children[0].children[0].onblur = function () {
        let _this = this
        setTimeout(() => {
          _this.removeAttribute('readonly')
        }, 200)
      }
    })
  },
   /**
   *  在树中通过值或者属性是否相等获取对应的节点列表
   */
    filterTreeToArr(arr, target, prop=null, tempArr = []) {
      let res = []
      arr.find(item => {
          let tempArr2 = [...tempArr, item]
          if (prop && item[prop] == target[prop] || !prop && item == target) {
              return res = tempArr2
          }
          if (item.children) {
              res = this.filterTreeToArr(item.children, target, prop, tempArr2)
              return res.length > 0
          }
      })
      return res
  },


}


export default {
  instance: utils,
  //注册插件
  install(Vue) {
    if (Vue.prototype.$Utils) {
      return;
    }
    Vue.prototype.$Utils = utils;
  }
}



